package com.boshao.classschedule.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;

import com.boshao.classschedule.R;
import com.boshao.classschedule.activity.MainActivity;
import com.boshao.classschedule.adapter.CalendarGridAdapter;
import com.boshao.classschedule.adapter.CalendarViewPagerAdapter;
import com.boshao.classschedule.adapter.TimeManagerAdapter;
import com.boshao.classschedule.listener.CalendarFragmentCallBack;
import com.boshao.classschedule.model.DateInfo;
import com.boshao.classschedule.model.LifeSchedule;
import com.boshao.classschedule.model.LifeScheduleDao;
import com.boshao.classschedule.utils.DataUtils;
import com.boshao.classschedule.utils.TimeUtils;

/**
 * 日历Fragment
 * @author boshao
 *
 */
public class CalendarFragment extends Fragment implements CalendarFragmentCallBack{
	private View mRootView;
	private ViewPager mViewPager;
	private TextView mTvYearMonth;
	private int mCurrentYear;
	private int mCurrentMonth;
	private int mCurrentDay;
	private int mSelectedDay = -1 ;
	private int mCurrPager;
	private static final int DEFAULT_PAGER = 500; 
	private static List<DateInfo> mCurrDateInfos = null;
	private List<DateInfo> mDateInfos = null;
	private AppOnItemClickListener mCalendarOnItemClickListener;
	private ListView mListView;
	public static TimeManagerAdapter mTimeManagerAdapter;
	private CalendarViewPagerAdapter mPagerAdapter;
//	private List<LifeSchedule> mLifeSchedules = new ArrayList<>();
	private static int changeYear;
	private static int changeMonth;
	
	public static CalendarFragment newInstance(){
		CalendarFragment calendarFragment = new CalendarFragment();
		return calendarFragment;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if(mRootView == null){
			initData();
			initView(inflater, container);			
		}else{
			((ViewGroup)mRootView.getParent()).removeView(mRootView);
		}
		return mRootView;
	}

	/**
	 * 初始日历view,(获取当前月的日历和农历)
	 * @param inflater
	 * @param container
	 */
	private void initView(LayoutInflater inflater, ViewGroup container) {
		mRootView = inflater.inflate(R.layout.fragment_calendar,container,false);
		mTvYearMonth = (TextView) mRootView.findViewById(R.id.tv_date_year_month);
		mTvYearMonth.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Calendar calendar = Calendar.getInstance();
				DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),new OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						int position = DataUtils.getPositionFromCurrent(TimeUtils.getFormatDate(year,monthOfYear+1), 
								TimeUtils.getFormatDate(mCurrentYear, mCurrentMonth));
						mViewPager.setCurrentItem(position);
						mTvYearMonth.setText(String.format("%04d年%02d月", year,monthOfYear+1));
					}
				},calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
				DatePicker picker = datePickerDialog.getDatePicker();
				picker.setMinDate(DataUtils
						.getMinCalendar(TimeUtils
								.getFormatDate(mCurrentYear, mCurrentMonth))
								.getTimeInMillis());
				picker.setMaxDate(DataUtils
						.getMaxCalendar(TimeUtils
								.getFormatDate(mCurrentYear, mCurrentMonth))
								.getTimeInMillis());
				picker.setCalendarViewShown(false);
				datePickerDialog.show();				
			}
		});
		mTvYearMonth.setText(String.format("%04d年%02d月", mCurrentYear, mCurrentMonth));
		mViewPager = (ViewPager) mRootView.findViewById(R.id.vp_calendar);	
		mCalendarOnItemClickListener = new AppOnItemClickListener();
		mPagerAdapter = new CalendarViewPagerAdapter(getActivity(),this);
		mViewPager.setAdapter(mPagerAdapter);
		mViewPager.setOffscreenPageLimit(3);
		mViewPager.setCurrentItem(DEFAULT_PAGER);
		mViewPager.setOnPageChangeListener(new CalendarOnPageChangeListener());
		mListView = (ListView) mRootView.findViewById(R.id.lv_ativity);
		mTimeManagerAdapter = new TimeManagerAdapter(getActivity(),this);
		mListView.setAdapter(mTimeManagerAdapter);
		mListView.setOnItemClickListener(mCalendarOnItemClickListener);
		mListView.setSelection(mCurrentDay-1);
	}

	private void initData() {
		mCurrentYear = TimeUtils.getCurrentYear();
		mCurrentMonth = TimeUtils.getCurrentMonth();
		mCurrentDay = TimeUtils.getCurrentDay();
		String formatDate = TimeUtils.getFormatDate(mCurrentYear, mCurrentMonth);
		try {
			mDateInfos = TimeUtils.initCalendar(formatDate, mCurrentMonth);
			mCurrDateInfos = mDateInfos;
			changeYear = mCurrentYear;
			changeMonth = mCurrentMonth;
		} catch (Exception e) {
		}
//		initLifeSchedule(mCurrentYear,mCurrentMonth);
	}

//	private void initLifeSchedule(int year,int month) {
//		int dayOfMonth = TimeUtils.getDaysOfMonth(year,month);
//		for(int i = 0;i < dayOfMonth;i++){
//			mLifeSchedules.add(null);
//		}		
//	}

	@Override
	public int getCurrentYear() {
		return mCurrentYear;
	}

	@Override
	public int getCurrentMonth() {
		return mCurrentMonth;
	}

	@Override
	public int getCurrentDay() {
		return mCurrentDay;
	}

	@Override
	public int getSelectedDay() {
		return mSelectedDay;
	}

	@Override
	public List<DateInfo> getDateInfos() {
		return mDateInfos;
	}	
	
	/**
	 * 日历滑动监听
	 * @author boshao
	 *
	 */
	private class CalendarOnPageChangeListener implements OnPageChangeListener{
		@Override
		public void onPageScrollStateChanged(int position) {
			
		}

		@Override
		public void onPageScrolled(int position, float arg1, int arg2) {
			
		}

		@Override
		public void onPageSelected(int position) {
			changeViewPageCalendar(position);
		}
		
		private void changeViewPageCalendar(int position) {
			((CalendarGridAdapter)mPagerAdapter.getCurrentGridView().getAdapter()).setSelectedPosition(-1);
			((CalendarGridAdapter)mPagerAdapter.getCurrentGridView().getAdapter()).notifyDataSetChanged();
			int year = TimeUtils.getTimeByPosition(position,mCurrentYear, mCurrentMonth, "year");
	    	int month = TimeUtils.getTimeByPosition(position, mCurrentYear, mCurrentMonth, "month");
	    	try {
				mCurrDateInfos = TimeUtils.initCalendar(TimeUtils.getFormatDate(year,month),month);
				mTimeManagerAdapter.setUpdateData(year,month,mCurrDateInfos);
//				initLifeSchedule(year,month);
			} catch (Exception e) {
			}
	    	mTvYearMonth.setText(String.format("%04d年%02d月", year, month));
			mCurrPager = position;
			changeYear = year;
			changeMonth = month;
		}
		
	}
	
	/**
	 * 日历ListView item监听
	 * @author boshao
	 *
	 */
	public class AppOnItemClickListener implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Log.e("ddddadafds","parent: "+parent+"view: "+"position: "+position+"id: "+"id");
			if(mPagerAdapter.getCurrentGridView() == parent){
				((CalendarGridAdapter)parent.getAdapter()).setSelectedPosition(position);
				((CalendarGridAdapter)parent.getAdapter()).notifyDataSetChanged();
				List<DateInfo> dateInfos = CalendarFragment.this.initDate(mCurrDateInfos);
				int selection = dateInfos.indexOf(mCurrDateInfos.get(position));
				mListView.setSelection(selection);
			}
			if(mListView == parent){
				if(((TimeManagerAdapter)parent.getAdapter()).getLifeSchedules().get(position) != null){
					TimeManagerFragment fragment = TimeManagerFragment.newInstance(CalendarFragment.this,((TimeManagerAdapter)parent.getAdapter()).getLifeSchedules().get(position));
					((MainActivity)getActivity()).addFragment(getActivity().getSupportFragmentManager(),fragment,fragment.getFragmentTag(),true);
				}
			}
		}
	}
	
	
	private List<DateInfo> initDate(List<DateInfo> dateInfos) {
		List<DateInfo> dInfos = new ArrayList<>();
		for (int i = 0,length = dateInfos.size(); i < length; i++) {
			DateInfo dateInfo = dateInfos.get(i);
			if(dateInfo.isThisMonth()){
				dInfos.add(dateInfo);
			}
		}
		return dInfos;
	}

	@Override
	public AppOnItemClickListener getCalendarOnItemClickListener() {
		return mCalendarOnItemClickListener;
	}	
	
	//更新日程UI
	public void refrashView(){
		mTimeManagerAdapter.setUpdateData(changeYear, changeMonth, mCurrDateInfos);
	}

}
